<script setup>
import { ref, reactive, onMounted } from 'vue';
import PostCard from './PostCard.vue';
import axios from "@/utils/axios.ts";

// 用户状态管理
const userStore = ref({
  isLoggedIn: false,
})

// 关注用户列表
const followList = ref([]);
// 推荐帖子数据
const posts = ref([]);
const isLoading = ref(false);
const hasMoreData = ref(true);
const page = ref(1);
const pageSize = ref(10);
const initialLoadChecked = ref(false);

const state = reactive({
  finished: false
});

// 是否显示更多关注
const showMoreFollows = ref(false);

// 切换显示更多关注
const toggleShowMoreFollows = () => {
  showMoreFollows.value = !showMoreFollows.value;
};

// 检查用户是否已登录
const isLoggedIn = () => {
  // 实际项目中应该检查真实的登录状态
  return localStorage.getItem('token') !== null;
};

// 检查用户是否有关注
const hasFollows = () => {
  return followList.value.length > 0;
};

// 初始化帖子列表
const initPost = async () => {
  console.log("初始化帖子列表");
  page.value = 1;
  state.finished = false;
  isLoading.value = false;
  initialLoadChecked.value = false;

  // 手动设置isLoading为true，确保van-list状态同步
  isLoading.value = true;
  console.log("初始化时设置isLoading为true");

  try {
    await loadPosts();
  } catch (error) {
    console.error("初始化帖子列表失败:", error);
  } finally {
    // 确保在loadPosts完成后重置isLoading
    isLoading.value = false;
    console.log("初始化完成，重置isLoading为false");
  }
};

// 加载帖子数据
const loadPosts = async () => {
  console.log("loadPosts被调用", "isLoading:", isLoading.value, "finished:", state.finished, "第几次:", page.value);

  console.log("开始加载数据，页码:", page.value);
  try {
    // 修复：确保请求体格式正确
    const res = await axios.post("/api/home/getFollow", {
      page: page.value,
      limit: pageSize.value,
    });

    console.log("请求返回结果:", res);

    // 修复：检查响应数据结构
    if (res.code == 200) {
      // 即使data为null也要处理
      const data = res.data || [];

      // 处理返回的数据
      if (page.value === 1) {
        console.log("初始化帖子列表，数据量:", data.length);
        posts.value = data;
      } else {
        // 确保data是数组
        const newData = Array.isArray(data) ? data : [];
        console.log("追加帖子列表，数据量:", newData.length);
        posts.value.push(...newData);
      }

      // 判断是否还有更多数据
      if (data.length < pageSize.value) {
        state.finished = true;
        console.log("已加载全部数据，当前总数:", posts.value.length);
      } else {
        page.value++;
        console.log("准备加载下一页，新页码:", page.value);
      }
    } else {
      console.error("获取帖子列表失败:", res.msg);
      // 请求失败时也标记为完成，避免无限加载
      state.finished = true;
    }
  } catch (error) {
    console.error("加载数据失败:", error);
    // 发生错误时也标记为完成，避免无限加载
    state.finished = true;
  }

  // 注意：不在loadPosts中修改isLoading状态，由onLoad函数负责
  console.log("loadPosts完成，finished:", state.finished, "posts数量:", posts.value.length);
};

// 加载更多数据
const onLoad = async () => {
  console.log("van-list触发onLoad事件", "isLoading:", isLoading.value, "finished:", state.finished);

  // 如果已完成，直接返回
  if (state.finished) {
    console.log("onLoad被阻止，因为已完成");
    return;
  }

  // 使用一个标记来防止重复加载
  if (isLoading.value) {
    console.log("检测到isLoading为true，忽略此次加载请求");
    return;
  }

  // 手动设置isLoading为true，确保状态同步
  isLoading.value = true;
  console.log("手动设置isLoading为true");

  try {
    await loadPosts();
  } catch (error) {
    console.error("onLoad过程中发生错误:", error);
  } finally {
    // 确保在loadPosts完成后重置isLoading
    isLoading.value = false;
    console.log("onLoad完成，重置isLoading为false");
  }
};

// 手动检查并加载更多数据
const checkAndLoadMore = () => {
  if (state.finished || isLoading.value) {
    console.log("手动检查：不需要加载更多，finished:", state.finished, "isLoading:", isLoading.value);
    return;
  }

  console.log("手动触发加载更多数据");
  onLoad();
};

// 处理滚动事件
const handleScroll = () => {
  if (!initialLoadChecked.value) return;

  // 检查是否滚动到底部
  const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
  const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
  const clientHeight = document.documentElement.clientHeight || window.innerHeight;

  // 当距离底部100px时触发加载
  if (scrollHeight - scrollTop - clientHeight < 100) {
    console.log("检测到滚动到底部，触发加载");
    checkAndLoadMore();
  }
};

// 删除帖子
const removePost = (postId) => {
  posts.value = posts.value.filter(post => post.postId !== postId);
};

// 获取关注用户列表
const fetchFollowList = async () => {
  try {
    // 修复：使用正确的API路径和请求方式
    const res = await axios.post("/api/home/getMyFollowUser", {
      page: 1,
      limit: 100 // 获取所有关注用户
    });

    if (res.code === 200 && res.data) {
      followList.value = res.data.map(user => ({
        id: user.userId,
        name: user.nickname,
        avatar: user.avatar || '/default-avatar.png',
        // 修复：使用正确的字段名
        fans: user.fansCount || 0 // 根据实际返回字段调整
      }));
    } else if (res.code === 500) {
      // 没有关注用户的情况
      followList.value = [];
    }
  } catch (error) {
    console.error("获取关注列表失败:", error);
    followList.value = []; // 出错时设为空数组
  }
};

// 生命周期钩子
onMounted(() => {
  console.log("Following组件挂载");
  fetchFollowList();
  initPost();

  // 添加滚动事件监听器
  window.addEventListener("scroll", handleScroll);

  // 设置初始加载检查为已完成，确保滚动加载正常工作
  // 延长时间确保第一次加载完全完成
  setTimeout(() => {
    initialLoadChecked.value = true;
    console.log("初始加载检查完成，允许滚动加载");
    // 确保状态同步
    isLoading.value = false;

    // 手动触发一次滚动加载检查
    checkAndLoadMore();
  }, 1000);
});
</script>

<template>
  <div class="following-container">
    <!-- 关注区域 -->
    <div class="follow-section">

      <!-- 未登录状态 -->
      <div v-if="!isLoggedIn()" class="empty-state">
        <p>未登录，请先登录查看关注列表</p>
        <button class="login-btn" @click="userStore.login">去登录</button>
      </div>

      <!-- 已登录但未关注任何人 -->
      <div v-else-if="!hasFollows()" class="empty-state">
        <p>您还没有关注任何人</p>
        <button class="discover-btn">去发现</button>
      </div>

      <!-- 已登录且有关注 -->
      <div v-else>
        <div class="follow-list">
          <div
              v-for="(follow, index) in (showMoreFollows ? followList : followList.slice(0, 5))"
              :key="follow.id"
              class="follow-item"
          >
            <img :src="follow.avatar" :alt="follow.name" class="avatar">
            <div class="follow-info">
              <h3>{{ follow.name }}</h3>
              <p>{{ follow.fans }} 粉丝</p>
            </div>
            <button class="follow-btn">已关注</button>
          </div>
        </div>

        <!-- 更多下拉线 -->
        <div v-if="followList.length > 5" class="more-container">
          <button class="more-btn" @click="toggleShowMoreFollows">
            {{ showMoreFollows ? '收起' : '更多' }}
            <span :class="['arrow', showMoreFollows ? 'up' : 'down']"></span>
          </button>
        </div>
      </div>
    </div>

    <!-- 为你推荐区域 -->
    <div class="recommend-section">
      <h2 class="section-title">为你推荐</h2>
      <div class="posts-container">
        <van-list
            :loading="isLoading"
            :finished="state.finished"
            :immediate-check="false"
            finished-text="没有更多了"
            @load="onLoad"
            :offset="100"
        >
          <PostCard
              v-for="post in posts"
              :key="post.postId"
              :post="post"
              @remove-post="removePost"
          />
        </van-list>
      </div>
    </div>
  </div>
</template>

<style scoped>
.following-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.section-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #eee;
}

/* 关注区域样式 */
.follow-section {
  margin-bottom: 30px;
}

.empty-state {
  text-align: center;
  padding: 40px 0;
  color: #666;
}

.login-btn, .discover-btn {
  margin-top: 16px;
  padding: 8px 24px;
  background-color: #ff6b6b;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.follow-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
}

.follow-item {
  display: flex;
  align-items: center;
  padding: 12px;
  border-radius: 8px;
  background-color: #f9f9f9;
}

.avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  margin-right: 12px;
}

.follow-info {
  flex: 1;
}

.follow-info h3 {
  margin: 0;
  font-size: 16px;
}

.follow-info p {
  margin: 4px 0 0;
  font-size: 12px;
  color: #666;
}

.follow-btn {
  padding: 6px 12px;
  background-color: #f0f0f0;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
}

.more-container {
  text-align: center;
  margin-top: 16px;
}

.more-btn {
  background: none;
  border: none;
  color: #666;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto;
}

.arrow {
  display: inline-block;
  width: 0;
  height: 0;
  margin-left: 6px;
  border-left: 5px solid transparent;
  border-right: 5px solid transparent;
}

.arrow.down {
  border-top: 5px solid #666;
}

.arrow.up {
  border-bottom: 5px solid #666;
}

/* 推荐区域样式 */
.recommend-section {
  margin-top: 30px;
}

/* 帖子列表容器 */
.posts-container {
  display: flex;
  flex-direction: column;
  gap: 0;
  margin: 0 -1.25rem;
}
</style>
